17. More on Document Structure

HTML Document Structure

The concept of code structure will come up frequently thoughout this Nanodegree program. That's because programmers write code not just for computers, but for people as well. Writing code that people can easily read is a VERY important idea in computer programming. And a huge part of writing good code is structuring it well.

If you've ever written an English essay, you're familiar with the purpose of indenting every paragraph. It's a visual marker that a new idea has begun. Indentation serves a similar purpose in writing code. Some languages have slightly different rules about proper indentation, but the concept is generally the same as in English - a new indent is a new idea.

One big difference between indenting programming languages and indenting English, however, is that an indentation level persists throughout an idea. In HTML particularly, the indentation level increases when an idea begins and decreases when an idea is finished. If this is a bit confusing, let's look at an example:

Let's dissect this code a bit:

1) The first line is something that should appear on every webpage you make. <!DOCTYPE html> defines the type of the document so the browser will render it correctly.

2) The <html> tag opens our document. Everything that shows on the webpage is placed within this tag.

3) The <head> tag defines metadata for our web page. This includes the title of the page (this is what appears in the top of your tab or browser window). Notice that the <head> tag is indented to a new level because the <html> tag was opened but not closed (a new idea was started but not completed). Moreso, the <title> tag is indented another level further (the <head> tag was opened but not closed).

4) The <title> tag is closed on the same line it was opened which we usually do if the content of a tag is short. On the other hand, the <head> tag is closed on a different line. The closing tag is indented to the same level as the matching opening one.

Now take a look at the contents of the <body> tag. Is there anything about the structure that is surprising to you? Notice that inside the <body> tags you have the content of the web page. You can see an <h1> tag that is indented just inside the body as well as a <p> tag that is on the same level of indentation as the <h1>. This is an important distinction. Both the header and paragraph are child elements of the body.